import java.io.*;
import java.util.*;

/**
 * Reads base.html, inserting apropriate info
 * Such as articles and location name
 * @author tomalteman
 *
 */
public class writePage {
	
	/**
	 * Called to start writing html file
	 * @param loc
	 * @param articles
	 */
	public static void write(String loc, ArrayList<article> articles, String page)
	{
		BufferedReader br;
		BufferedWriter wr;
		String line, out;
		
		//Make loc capitalised
		if(loc.length()>1) loc = loc.substring(0,1).toUpperCase() + loc.substring(1).toLowerCase();
		
		//Open base file and index file
		try {
			br = new BufferedReader(new FileReader("web/"+page+"base.html"));
			wr = new BufferedWriter(new FileWriter("web/" + page +".html"));
			
			//Read in lines from base to use in index
			while((line = br.readLine()) != null)
			{
				//Add title
				if(line.startsWith("<!--dotitle")) out = "<title> Automated Local News for " + loc + ". Powered by AlterNews.com</title>";
				else if(line.startsWith("<!--doheader")) out = "<h1 id=\"page-title\"><a href=\"#\"> Automated Local News for " + loc + "</a></h1>";
				else if(line.startsWith("<!--doarticles"))
				{
					writeArticles(wr,articles);
					out="";
				}
				else out = line;
				wr.write(out);
				wr.newLine();
			}
			
			br.close();
			wr.close();
		} catch (Exception e)
		{
			err(e.toString());
		}
		
	}
	
	/**
	 * Write html for each article
	 * @param wr
	 * @param articles
	 */
	private static void writeArticles(BufferedWriter wr, ArrayList<article> articles)
	{
		article art;
		String out;
		
		
		//Loop through each article
		for(int i=0;i<articles.size();i++)
		{
			art = articles.get(i);
			
			//System.out.println(art.getTitle());
			//System.out.println(art.getDescription());
			
			//Output string is
			out = 
				"<div class=\"post\">\n" +
				"<h2><a href=\"" + art.getLink() + "\">" + art.getTitle() + "</a></h2>\n" +
				"<p class=\"posted\"><span class=\"posttime\">" + art.getTime() + "/ <b>" + art.getSource() + "</b></span><span class=\"comments\"><a href=\"" + art.getLink() + "\">Go to article</a></span></p>\n" +
				"<div class=\"entry\">\n" +
				"<p>" + art.getDescription() + "</p>\n" +
				"<blockquote><p>" + art.getText() + "</blockquote></p>" +
				"</div>\n" +
				"<p class=\"tags\">"+"<b>Location: </b>"+art.location +"<b> Local Rank: </b>"+ art.localRank+"<b> Topic: </b>"+art.category +" </p>\n" +
				"</div>\n";
			
			//Write to index
			try {
				wr.write(out);
			} catch (Exception e)
			{
				err(e.toString());
			}
		}
		
	}
	
	/**
	 * Error method
	 * @param s
	 * @return 
	 */
	
	private static void err(String s)
	{
		//Error printing
		System.err.println(s);
		System.exit(1);        
	}
}
